define(function (require, exports, module) {

    require.async('webuploader', function () {
        if(typeof KindEditor == 'undefined') return;
        KindEditor.ready(function (K) {
            (function($){
                $(function () {

                var uploaderOptions = ['info','desc','intro'];

                $.each(uploaderOptions, function(i,n){
                    var $aEditorName = $('textarea[name="'+n+'"]');
                    if($aEditorName && $aEditorName.length != 0){
                        var $aDndElem = $aEditorName.prev('.ke-container').find('.ke-edit-iframe').eq(0).contents().find('.ke-content').eq(0);
                        dndUploader($aDndElem, n);
                    }
                });

                function dndUploader(elem,name){
                    // 不支持IE
                    var ua = navigator.userAgent.toLowerCase();
                    var isIE = /trident/g.test(ua);
                    if (!isIE) {
                        if (!WebUploader.Uploader.support()) {
                            alert('Web Uploader 不支持您的浏览器！如果你使用的是IE浏览器，请尝试升级 flash 播放器');
                            throw new Error('WebUploader does not support the browser you are using.');
                        }

//                        var dndElem =  $('.ke-edit-iframe').eq(0).contents().find('.ke-content').eq(0);
                        var dndElem = elem;
                        dndElem.css({
                            'position':'absolute',
                            'width': '100%',
                            'height': '100%',
                            'left': '0',
                            'top': '0',
                            'padding': '0'
                        });
                        var $queueList = $('.queueList').eq(0).append('<ul class="filelist"></ul>');
                        var $filelist = $('#uploader_box .filelist');
                        var $statusBar = $('#uploader_box .statusBar');
//                    var $progress = $('#uploader_box .statusBar .progress');
                        var $uploadBtn = $('#uploader_box .uploadBtn');
                        var $closeBtn = $('#close_uploader_container');
                        var $info = $statusBar.find('.info');
                        var fileCount = 0;
                        var fileSize = 0;
                        var state = 'pedding';

                        $('.ke-edit').css('margin','5px');

                        var uploader = WebUploader.create({
                            dnd: dndElem,
                            paste: dndElem,
                            accept: {
                                title: 'Images',
                                extensions: 'gif,jpg,jpeg,bmp,png',
                                mimeTypes: 'image/*'
                            },
                            swf: '/static/kindeditor/plugins/webuploader/dist/Uploader.swf',

                            disableGlobalDnd: true,
                            chunked: true,
                            server: webuploader_server,
                            fileNumLimit: 300,
                            fileSizeLimit: 200 * 1024 * 1024,    // 200 M
                            fileSingleSizeLimit: DNDUPLOADERSINGLESIZE *1024    // 2 M
                        });

                        // 添加“添加文件”的按钮，
                        uploader.addButton({
                            id: '#filePicker2',
                            label: '继续添加'
                        });

                        // 与服务器交互
                        uploader.on('uploadAccept', function(object,ret){
                        	
                        	if(ret.result != null && ret.result.url){
                                var iImg = '<img src="' + ret.result.url + '" >';
                                // 插入编辑器
                                K.insertHtml('textarea[name="'+name+'"]', iImg);
                                updateStatus();

                            }else{
                                alert( ret.error.message );
                                return false;
                            }

                        });

                        // 添加文件
                        function addFile(file){
                        	// 图片列表
                            var $li = $('<li id="' + file.id + '">' +
                                '<p class="title">' + file.name + '</p>' +
                                '<p class="imgWrap"></p>' +
                                '<p class="progress"><span></span></p>' +
                                '</li>');
                            $btns = $('<div class="file-panel">' +
                                '<span class="cancel">删除</span></div>').appendTo($li);
                            var $progress = $li.find('p.progress span');
                            var $imgWrap = $li.find('p.imgWrap');
                            var $uploadInfo = $('<p class="error"></p>');
                            var showError = function (code) {
                                switch (code) {
                                    case 'exceed_size':
                                        text = '文件大小超出';
                                        break;

                                    case 'interrupt':
                                        text = '上传暂停';
                                        break;

                                    default:
                                        text = '上传失败，请重试';
                                        break;
                                }

                                $uploadInfo.text(text).appendTo($li);
                            };

                            if (file.getStatus() === 'invalid') {
                                showError(file.statusText);
                            } else {
                                $imgWrap.text('预览中');
                                uploader.makeThumb(file, function(error, ret){
                                    if(error){
                                        $imgWrap.text('预览错误');
                                        return;
                                    }

                                    var img = '<img src="'+ret+'"/>';
                                    $imgWrap.empty().append(img);

                                }, 110, 110 );
                            }


                            file.on('statuschange', function (cur, prev) {


                                if (prev === 'progress') {
//                                $prgress.hide().width(0);
                                    $progress.text('上传中');
                                } else if (prev === 'queued') {
                                    $li.off('mouseenter mouseleave');
//                                $btns.remove();
                                }

                                // 成功
                                if (cur === 'error' || cur === 'invalid') {
                                    console.log(file.statusText);
                                    showError(file.statusText);
                                } else if (cur === 'interrupt') {
                                    showError('interrupt');
                                } else if (cur === 'queued') {
                                    showError('queued');
                                } else if (cur === 'progress') {
//                                $info.remove();
//                                showError('progress');
                                } else if (cur === 'complete') {
//                                $li.append('<span class="success"></span>');
//                                showError('complete');
                                    $li.append('<span class="success"></span>');
                                }

                                $li.removeClass('state-' + prev).addClass('state-' + cur);
                            });


                            /*$li.on('mouseenter', function () {
                             $btns.stop().animate({height: 30});
                             });

                             $li.on('mouseleave', function () {
                             $btns.stop().animate({height: 0});
                             });*/

                            $filelist.append($li);

                            var $ulLi = $filelist.find('li');
                            $.each($ulLi, function(){
                                $(this).hover(function(){
                                    $(this).find('div.file-panel').stop().animate({height: 30});
                                },function(){
                                    $(this).find('div.file-panel').stop().animate({height: 0});
                                });
                            });

                            $btns.on('click', 'span.cancel', function(){
                                uploader.removeFile(file);
                            })

                        }

                        uploader.on('fileDequeued', function (file) {
                            fileCount--;
                            fileSize -= file.size;

                            if (!fileCount) {
                                setState('pedding');
                            }
                            var $ili = $('#' + file.id);
                            $ili.off().find('.file-panel').off().end().remove();

                            updateStatus();

                        });


                        // 隐藏层的函数
                        function hideContainer() {
                            fileCount = 0;
                            fileSize = 0;
                            uploader.reset();
                            $('#uploader_container').fadeOut(100, function () {
                                $('#uploader_container').removeClass('container');
                                $('html,body,#uploader_container').removeAttr('style');
                                $('.filelist').children().remove();
                                $('.uploadBtn').removeClass('disabled');
                            });
                        }

                        // 计算上传个数与总大小
                        function updateStatus() {
                            var text = '', stats;

                            if (state === 'ready') {
                                text = '选中' + fileCount + '张图片，共' +
                                    WebUploader.formatSize(fileSize) + '。';
                            } else if (state === 'confirm') {
                                stats = uploader.getStats();
                                if (stats.uploadFailNum) {
                                    text = '已成功上传' + stats.successNum + '张照片，' +
                                        stats.uploadFailNum + '张照片上传失败，<a class="retry" href="#">重新上传</a>失败图片';
                                    /*text = '已成功上传' + stats.successNum + '张照片，' +
                                     stats.uploadFailNum + '张照片上传失败，<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'*/
                                }

                            } else {
                                stats = uploader.getStats();
                                text = '共' + fileCount + '张（' +
                                    WebUploader.formatSize(fileSize) +
                                    '），已上传' + stats.successNum + '张';

                                if (stats.uploadFailNum) {
                                    text += '，失败' + stats.uploadFailNum + '张';
                                }
                            }

                            $info.html(text);
                        }

                        function setState(val) {
                            var file, stats;

                            if (val === state) {
                                return;
                            }

                            $uploadBtn.removeClass('state-' + state);
                            $uploadBtn.addClass('state-' + val);
                            state = val;

                            switch (state) {
                                case 'pedding':
//                                $statusBar.addClass('element-invisible');
                                    hideContainer();
                                    break;

                                case 'ready':
                                    $('#filePicker2').removeClass('element-invisible');
                                    $statusBar.removeClass('element-invisible');
                                    uploader.refresh();
                                    break;

                                case 'uploading':
                                    $('#filePicker2').addClass('element-invisible');
                                    $uploadBtn.text('暂停上传');
                                    break;

                                case 'paused':
                                    $uploadBtn.text('继续上传');
                                    break;

                                case 'confirm':
                                    $uploadBtn.text('开始上传').addClass('disabled');

                                    stats = uploader.getStats();
                                    if (stats.successNum && !stats.uploadFailNum) {
                                        setState('finish');
                                        return;
                                    }
                                    break;
                                case 'finish':
                                    stats = uploader.getStats();
                                    if (stats.successNum) {
                                        console.log('finish');

//                                    setTimeout(function(){
                                        hideContainer();
//                                    }, 3000);

                                    } else {
                                        // 没有成功的图片，重设
                                        state = 'done';
                                        location.reload();
                                    }
                                    break;
                            }

                            updateStatus();
                        }

                        // 当文件加入队列
                        uploader.on('fileQueued', function(file){
                            // 交互
                            $('html,body').css('overflow', 'hidden');
                            $('#uploader_container').addClass('container').show();
                            $('#uploader_box').show();
                            $('.webuploader-pick').next('div').css({
                                left: '10px',
                                width: '94px',
                                height: '42px'
                            });



                            fileCount++;
                            fileSize += file.size;

                            // 上传按钮
                            if (fileCount === 1) {
                                $statusBar.show();
                            }

                            addFile(file);
                            setState('ready');
                            updateStatus();
                        });

                        // 点击上传
                        $uploadBtn.on('click', function(){
                            if ($(this).hasClass('disabled')) {
                                return false;
                            }
                            $(this).addClass('disabled');

                            if (state === 'ready') {
                                uploader.upload();
                            } else if (state === 'paused') {
                                uploader.upload();
                            } else if (state === 'uploading') {
                                uploader.stop();
                            }
                        });


                        uploader.on('all', function (type) {
                            var stats;
                            switch (type) {
                                case 'uploadFinished':
                                    setState('confirm');
                                    break;

                                case 'startUpload':
                                    setState('uploading');
                                    break;

                                case 'stopUpload':
                                    setState('paused');
                                    break;

                            }
                        });



                        // uploader 出错
                        uploader.on('error',function (code) {
                            var msg = '';
                            switch (code){
                                case 'Q_EXCEED_NUM_LIMIT':
                                    msg = '最多添加' + this.options.fileNumLimit + '个文件';
                                    break;
                                case 'Q_EXCEED_SIZE_LIMIT':
                                    msg = '文件总大小最大' + WebUploader.formatSize(this.options.fileSingleSizeLimit);
                                    break;
                                case 'F_EXCEED_SIZE':
                                    msg = '单个文件最大' + WebUploader.formatSize(this.options.fileSingleSizeLimit);
                                    break;
                                case 'F_DUPLICATE':
                                    msg = '不允许上传重复的文件';
                                    break;
                                default :
                                    msg = code;
                            }
                            alert('友情提示: ' + msg);
                        });

                        // 关闭层并重置uploader
                        $closeBtn.on('click', function(){

                            hideContainer();
                        });

                        $info.on('click', '.retry', function () {
                            uploader.retry();
                        });

                        /*$info.on('click', '.ignore', function () {
                         console.log('如何忽略');
                         });*/

                    }
                }
            });
            })(jq183);
            
        });
    });
});
